import { useState, useEffect } from "react"
import { useLocation, useNavigate } from "react-router-dom"
import { roleCreate, roleEdit, roleList } from "@/api/index"
import { Button, Col, Form, Input, Tree, Select, Space, message } from "antd"

const RoleAction = () => {
  const { pathname, search } = useLocation()
  const navigate = useNavigate()
  const _id = search.split("=")[1]
  const type = pathname.split("/")[pathname.split("/").length - 1]
  const typeName = { add: "新建", edit: "编辑", detail: "查看" }
  const typeApi = { add: roleCreate, edit: roleEdit }
  const routers = JSON.parse(sessionStorage.getItem("routers"))[0] || []
  const routerTree = (data) => {
    if (!data && !data.children) return []
    let { children } = data
    return children.map((item) => {
      if (item.children) {
        return {
          title: item.name,
          path: item.path,
          key: item._id,
          children: item.children
        }
      }
      return item
    })
  }
  const treeData = routerTree(routers)
  const [keys, setKeys] = useState([])
  const [checkedKeys, setCheckedKeys] = useState([])
  const [form] = Form.useForm()
  const { Option } = Select
  const formItemLayout = {
    labelCol: {
      span: 6
    },
    wrapperCol: {
      span: 14
    }
  }
  const flag = type !== "add"
  const columns = [
    {
      label: "角色名称",
      dataIndex: "name",
      name: "name",
      type: "input",
      rules: [
        {
          required: type !== "detail",
          message: "角色名称不能为空"
        },
        {
          max: 10,
          message: "角色名称不能超过10个字"
        },
        {
          min: 3,
          message: "角色名称不能少于3个字"
        }
      ],
      columnsInfo: {
        disabled: type === "detail",
        placeholder: "请输入角色名称"
      }
    },
    {
      label: "角色状态",
      name: "state",
      type: "select",
      rules: [
        {
          required: type !== "detail",
          message: "请选择角色状态"
        }
      ],
      columnsInfo: {
        disabled: type === "detail",
        placeholder: "请选择角色状态",
        options: [
          {
            title: "启用",
            value: 0
          },
          {
            title: "禁用",
            value: 1
          }
        ]
      }
    },
    {
      label: "权限状态",
      name: "state",
      type: "tree",
      rules: [
        {
          required: type !== "detail",
          message: "请分配角色权限"
        }
      ],
      columnsInfo: {
        disabled: type === "detail",
        checkable: true,
        placeholder: "请分配角色权限",
        checkStrictly: true,
        checkedKeys: checkedKeys,
        onCheck: (checkedKey) => onCheck(checkedKey),
        treeData: treeData
      }
    }
  ]

  useEffect(() => {
    getRoleList()
  }, [])
  const getChildren = () => {
    const children = columns.map((item, index) => {
      return (
        <Col span={6} key={index}>
          {item.type === "input" && (
            <Form.Item name={item.name} label={item.label} rules={item.rules}>
              <Input
                placeholder={item.columnsInfo.placeholder}
                disabled={item.columnsInfo.disabled}
              />
            </Form.Item>
          )}
          {item.type === "select" && (
            <Form.Item name={item.name} label={item.label} rules={item.rules}>
              <Select
                placeholder={item.columnsInfo.placeholder}
                disabled={item.columnsInfo.disabled}
              >
                {item.columnsInfo.options.map((option) => {
                  return (
                    <Option value={option.value} key={option.value}>
                      {option.title}
                    </Option>
                  )
                })}
              </Select>
            </Form.Item>
          )}
          {item.type === "tree" && (
            <Form.Item
              name={item.name}
              label={item.label}
              rules={item.rules}
              style={{
                height: "400px"
              }}
            >
              <Tree treeData={item.columnsInfo.treeData} {...item.columnsInfo}></Tree>
            </Form.Item>
          )}
        </Col>
      )
    })
    return [...children]
  }
  const onCheck = (checkedKey) => {
    setKeys(() => [...checkedKey.checked])
    // console.log(checkedKey,)
    setCheckedKeys(() => [...checkedKey.checked])
  }
  const getData = async (value) => {
    let valueCopy = JSON.parse(JSON.stringify(value))
    valueCopy.menu_id.push("654b707722c29648bfc14e8a", "655ad5bf0a4f00000c005762")
    const { code } = await typeApi[type](type !== "add" ? { _id, ...value } : { ...valueCopy })
    if (code === 200) {
      message.success("提交成功")
      onReset()
    }
  }

  const getRoleList = async () => {
    const { pageData } = await roleList({ _id })
    setCheckedKeys(flag ? pageData[0].menu_id : [])
    flag && form.setFieldsValue({ ...pageData[0] })
  }
  const onFinish = (value) => {
    // eslint-disable-next-line camelcase
    let menu_id = [...keys]
    // eslint-disable-next-line camelcase
    getData({ ...value, menu_id })
  }
  const onReset = () => {
    form.resetFields()
    navigate(-1)
  }

  return (
    <div>
      <div>
        <h3>{typeName[type]}角色列表</h3>
      </div>
      <div>
        <Form
          style={{
            height: "540px"
          }}
          form={form}
          name="validate_other"
          onFinish={onFinish}
          {...formItemLayout}
        >
          <Col gutter={6}>{getChildren()}</Col>
          <Form.Item>
            <Space size={"middle"}>
              {type !== "detail" && (
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              )}

              <Button htmlType="button" onClick={onReset}>
                返回
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default RoleAction
